package com.innovation.ic.im.end.web.controller.im_erp9;

import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.pojo.ApiResult;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqExchangeMap;
import com.innovation.ic.im.end.base.service.im_erp9.GroupMessageReceiverService;
import com.innovation.ic.im.end.base.value.config.ZookeeperParamConfig;
import com.innovation.ic.im.end.base.vo.im_erp9.GroupRetractionVo;
import com.innovation.ic.im.end.base.value.config.RabbitMqParamConfig;
import com.innovation.ic.im.end.web.controller.AbstractController;
import com.innovation.ic.im.end.web.thread.HandleRetractionGroupMsgThread;
import com.innovation.ic.im.end.base.thread.web.SendRabbitMqMessageThread;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 默认群组未读消息API
 */
@Api(value = "默认群组未读消息API", tags = "GroupOfflineMessageController")
@RestController
@RequestMapping("/api/v1/groupMessageReceiver")
@DefaultProperties(defaultFallback = "defaultFallback")
public class GroupMessageReceiverController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(GroupMessageReceiverController.class);

    @Resource
    private GroupMessageReceiverService groupMessageReceiverService;

    @Resource
    private RabbitMqParamConfig rabbitMqParamConfig;

    @Resource
    private ZookeeperParamConfig zookeeperParamConfig;

    /**
     * 恢复默认群组未读消息
     * @return 返回处理结果
     */
    @HystrixCommand
    @ApiOperation(value = "恢复默认群组未读消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "默认群组id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/restore/{groupId}/{toUserAccount}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> restore(@PathVariable("groupId") String groupId,
                                                      @PathVariable("toUserAccount") String toUserAccount,
                                                      HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(groupId)|| StringUtils.isEmpty(toUserAccount)) {
            String message = "调用接口【/api/v1/groupMessageReceiver/restore/{groupId}/{toUserAccount}时，" +
                    "参数groupId和toUserAccount不能为空";
            log.warn(message);
            ApiResult<Integer> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 通过groupMessageId与toUserAccount 修改消息状态为已读
        ServiceResult<Integer> result = groupMessageReceiverService.restoreGroupMessageReceiver(groupId, toUserAccount);

        // 推送rabbitMq消息
        List<String> list = new ArrayList<>();
        list.add(toUserAccount);
        SendRabbitMqMessageThread sendRabbitMqMessageThread = new SendRabbitMqMessageThread(list, rabbitMqParamConfig.getExchange().get(RabbitMqExchangeMap.CURRENT_EXCHANGE));
        threadPoolManager.execute(sendRabbitMqMessageThread);

        ApiResult<Integer> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 默认群组，撤回消息
     * @return 返回处理结果
     */
    @HystrixCommand
    @ApiOperation(value = "默认群组，撤回消息")
    @ApiImplicitParam(name = "groupRetractionVo", value = "默认群组，撤回消息的vo类", required = true, dataType = "GroupRetractionVo")
    @RequestMapping(value = "/retraction", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> retraction(@RequestBody GroupRetractionVo groupRetractionVo, HttpServletRequest request, HttpServletResponse response) {
        if (null == groupRetractionVo || StringUtils.isEmpty(groupRetractionVo.getGroupMessageId())
                || null == groupRetractionVo.getRetractionTime()) {
            String message = "调用接口【/api/v1/groupMessageReceiver/retraction时，" +
                    "参数groupMessageId和retractionTime不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 处理撤回消息数据
        HandleRetractionGroupMsgThread handleRetractionGroupMsgThread = new HandleRetractionGroupMsgThread(groupMessageReceiverService, groupRetractionVo, rabbitMqParamConfig, zookeeperParamConfig, threadPoolManager);
        threadPoolManager.execute(handleRetractionGroupMsgThread);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(Boolean.TRUE);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}